package com.flower.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.flower.model.dto.CustomerDTO;
import com.flower.model.dto.CustomerPageQueryDTO;
import com.flower.model.entity.Customer;
import com.flower.result.PageResult;
import com.flower.result.Result;
import com.flower.service.CustomerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@SuppressWarnings("all")
/**
 *@ClassName CustomerController
 *@Description TODO
 *@Author @O_o  GW__
 *@Date 2025/6/13 15:34
 *@Version 1.0
 */
@Api("客户管理")
@RestController
@RequestMapping("/customer")
@Slf4j
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    @GetMapping("/page")
    @ApiOperation("分页查询客户信息")
    public Result<PageResult> pageQuery(CustomerPageQueryDTO customerPageQueryDTO) {
        log.info("分页查询");
        PageResult pageResult = customerService.page(customerPageQueryDTO);
        return Result.success(pageResult);
    }

    @PostMapping
    @ApiOperation("添加/修改客户信息")
    public Result add(@RequestBody CustomerDTO customerDTO) {
        log.info("添加/修改");
        customerService.addOrUpdate(customerDTO);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除客户信息")
    public Result delete(@PathVariable Integer id) {
        log.info("删除");
        customerService.deleteCustomer(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    @ApiOperation("批量删除客户信息")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        log.info("批量删除");
        customerService.deleteCustomerBatch(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(customerService.list());
    }

    @GetMapping("/findsale")
    public Result findsale() {
        return Result.success(customerService.nameValidate());
    }

    @GetMapping("/findwholesale")
    public Result findwholesale() {
        return Result.success(customerService.saleValidate());
    }

    /**
     * 导出接口
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response)throws Exception{
        //从数据库查询出所有的数据
        List<Customer> list = customerService.list();
        //通过工具类创建writer写出到磁盘路径
        //ExcelWriter writer = ExcelUtil.getWriter(filesUploadPath+ "/用户信息.xlsx");
        //在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);
        //自定义标题别名
        writer.addHeaderAlias("id","客户编号");
        writer.addHeaderAlias("cusName","名称");
        writer.addHeaderAlias("cusSort","类别");
        writer.addHeaderAlias("cusPhone","联系方式");
        writer.addHeaderAlias("cusAddress","地址");
        writer.addHeaderAlias("cusCost","总花费");
        writer.addHeaderAlias("cusPay","总支付");


        //一次性写出list内的对象到Excel，使用默认样式，强制输出标题
        writer.write(list,true);
        //设置浏览器响应格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("客户信息","UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out,true);
        out.close();
        writer.close();
    }
    /**
     * excel 导入
     * @param file
     * @throws Exception
     */
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception{
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);
        //方式一：通过javabean的方式读取Excel内的对象，但是要求表头必须是英文，跟Javabean的属性要对应起来。
        //List<Manager> list = reader.readAll(Manager.class);

        //方式二：忽略表头的中文，直接读取表的内容
        List<List<Object>> list = reader.read(1);
        List<Customer> customers = CollUtil.newArrayList();
        for (List<Object> row : list){
            Customer customer=new Customer();
            customer.setCusName(row.get(0).toString());
            customer.setCusSort(row.get(1).toString());
            customer.setCusPhone(row.get(2).toString());
            customer.setCusAddress(row.get(3).toString());
            customer.setCusCost(row.get(4).toString());
            customer.setCusPay(row.get(5).toString());
            customers.add(customer);
        }
        customerService.saveBatch(customers);//插入数据库
        return Result.success(true);

    }
}
